import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, TouchableOpacity, StyleSheet, Alert, Image, SafeAreaView, StatusBar, TouchableWithoutFeedback, Keyboard, ScrollView, ActivityIndicator } from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { Ionicons, MaterialIcons, MaterialCommunityIcons, FontAwesome } from '@expo/vector-icons';
import { Link, router } from 'expo-router';
import { Checkbox } from 'react-native-paper';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useAppDispatch, useAppSelector } from './store/hooks';
import { registerUser, clearError } from './store/userSlice';

// 注册页面组件
export default function RegisterScreen() {
  const insets = useSafeAreaInsets(); // 获取安全区域的尺寸
  
  const [studentId, setStudentId] = useState('');
  const [email, setEmail] = useState('');
  const [phoneNumber, setPhoneNumber] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [agreeTerms, setAgreeTerms] = useState(false);
  
  const dispatch = useAppDispatch();
  const { loading, error } = useAppSelector(state => state.user);

  // 显示错误提示
  useEffect(() => {
    if (error) {
      Alert.alert('注册失败', error, [
        { text: '确定', onPress: () => dispatch(clearError()) }
      ]);
    }
  }, [error, dispatch]);

  // 显示社交登录功能开发中的提示
  const showDevelopingAlert = () => {
    Alert.alert(
      '功能开发中',
      '该功能正在开发中，敬请期待！',
      [{ text: '确定', style: 'default' }]
    );
  };

  // 验证邮箱格式
  const isValidEmail = (email: string) => {
    if (!email) return true; // 邮箱选填
    const emailRegex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
    return emailRegex.test(email);
  };

  // 验证手机号格式
  const isValidPhone = (phone: string) => {
    if (!phone) return true; // 手机号选填
    const phoneRegex = /^1[3-9]\d{9}$/; // 中国大陆手机号
    return phoneRegex.test(phone);
  };

  // 处理注册按钮点击
  const handleRegister = () => {
    // 表单验证
    if (!studentId || studentId.length !== 9 || !/^\d+$/.test(studentId)) {
      Alert.alert('提示', '请输入9位数字学号');
      return;
    }
    
    if (!password) {
      Alert.alert('提示', '请输入密码');
      return;
    }

    if (password !== confirmPassword) {
      Alert.alert('提示', '两次输入的密码不一致');
      return;
    }

    if (!agreeTerms) {
      Alert.alert('提示', '请阅读并同意用户协议和隐私政策');
      return;
    }

    if (email && !isValidEmail(email)) {
      Alert.alert('提示', '请输入正确的邮箱格式');
      return;
    }

    if (phoneNumber && !isValidPhone(phoneNumber)) {
      Alert.alert('提示', '请输入正确的手机号格式');
      return;
    }

    // 调用注册API
    dispatch(registerUser({
      studentId,
      userPassword: password,
      checkPassword: confirmPassword,
      email: email || undefined,
      phone: phoneNumber || undefined
    }))
      .unwrap()
      .then(() => {
        Alert.alert(
          '注册成功',
          '您已成功注册，请登录',
          [
            { 
              text: '确定', 
              onPress: () => router.replace('/login')
            }
          ]
        );
      });
  };

  return (
    <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
      <View style={styles.container}>
        <StatusBar barStyle="light-content" />
        
        {/* 顶部渐变背景区域 */}
        <LinearGradient
          colors={['#673ab7', '#5e35b1', '#3949ab']}
          style={[
            styles.header,
            { paddingTop: insets.top + 20 } // 添加顶部安全区域的padding
          ]}
        >
          <TouchableOpacity 
            style={styles.backButton}
            onPress={() => {
              // 使用replace替代navigate，避免导航堆栈问题
              router.replace("/login" as any);
            }}
            disabled={loading}
          >
            <Ionicons name="arrow-back" size={24} color="#ffffff" />
            <Text style={styles.backButtonText}>返回登录</Text>
          </TouchableOpacity>
          
          <View style={styles.headerTextContainer}>
            <Text style={styles.welcomeText}>创建账户</Text>
            <Text style={styles.subHeaderText}>开始您的精彩体验</Text>
          </View>
        </LinearGradient>

        {/* 表单区域 */}
        <ScrollView style={styles.formContainer} showsVerticalScrollIndicator={false}>
          {/* 学号输入框 */}
          <View style={styles.inputGroup}>
            <Text style={styles.label}>学号 <Text style={styles.requiredMark}>*</Text></Text>
            <View style={styles.inputContainer}>
              <MaterialIcons name="badge" size={20} color="#888" style={styles.inputIcon} />
              <TextInput
                style={styles.input}
                placeholder="请输入9位数字学号"
                keyboardType="numeric"
                maxLength={9}
                value={studentId}
                onChangeText={setStudentId}
                editable={!loading}
              />
            </View>
          </View>

          {/* 电子邮箱输入框 */}
          <View style={styles.inputGroup}>
            <Text style={styles.label}>电子邮箱 <Text style={styles.optionalMark}>(选填)</Text></Text>
            <View style={styles.inputContainer}>
              <MaterialIcons name="email" size={20} color="#888" style={styles.inputIcon} />
              <TextInput
                style={styles.input}
                placeholder="请输入电子邮箱 (选填)"
                keyboardType="email-address"
                value={email}
                onChangeText={setEmail}
                editable={!loading}
              />
            </View>
          </View>

          {/* 手机号码输入框 */}
          <View style={styles.inputGroup}>
            <Text style={styles.label}>手机号码 <Text style={styles.optionalMark}>(选填)</Text></Text>
            <View style={styles.inputContainer}>
              <MaterialIcons name="phone" size={20} color="#888" style={styles.inputIcon} />
              <TextInput
                style={styles.input}
                placeholder="请输入手机号码 (选填)"
                keyboardType="phone-pad"
                value={phoneNumber}
                onChangeText={setPhoneNumber}
                editable={!loading}
              />
            </View>
          </View>

          {/* 密码输入框 */}
          <View style={styles.inputGroup}>
            <Text style={styles.label}>密码 <Text style={styles.requiredMark}>*</Text></Text>
            <View style={styles.inputContainer}>
              <Ionicons name="lock-closed" size={20} color="#888" style={styles.inputIcon} />
              <TextInput
                style={styles.input}
                placeholder="请设置密码"
                secureTextEntry={!showPassword}
                value={password}
                onChangeText={setPassword}
                editable={!loading}
              />
              <TouchableOpacity 
                style={styles.passwordToggle}
                onPress={() => setShowPassword(!showPassword)}
                disabled={loading}
              >
                <Ionicons name={showPassword ? "eye" : "eye-off"} size={20} color="#888" />
              </TouchableOpacity>
            </View>
          </View>

          {/* 确认密码输入框 */}
          <View style={styles.inputGroup}>
            <Text style={styles.label}>确认密码 <Text style={styles.requiredMark}>*</Text></Text>
            <View style={styles.inputContainer}>
              <Ionicons name="lock-closed" size={20} color="#888" style={styles.inputIcon} />
              <TextInput
                style={styles.input}
                placeholder="请再次输入密码"
                secureTextEntry={!showConfirmPassword}
                value={confirmPassword}
                onChangeText={setConfirmPassword}
                editable={!loading}
              />
              <TouchableOpacity 
                style={styles.passwordToggle}
                onPress={() => setShowConfirmPassword(!showConfirmPassword)}
                disabled={loading}
              >
                <Ionicons name={showConfirmPassword ? "eye" : "eye-off"} size={20} color="#888" />
              </TouchableOpacity>
            </View>
          </View>

          {/* 用户协议和隐私政策 */}
          <View style={styles.termsContainer}>
            <Checkbox
              status={agreeTerms ? 'checked' : 'unchecked'}
              onPress={() => setAgreeTerms(!agreeTerms)}
              color="#5e35b1"
              disabled={loading}
            />
            <Text style={styles.termsText}>
              我已阅读并同意 
              <Text style={styles.termsLink} onPress={() => showDevelopingAlert()}>《用户协议》</Text> 和 
              <Text style={styles.termsLink} onPress={() => showDevelopingAlert()}>《隐私政策》</Text>
            </Text>
          </View>

          {/* 注册按钮 */}
          <TouchableOpacity 
            style={[
              styles.registerButton, 
              (loading || !agreeTerms) && styles.registerButtonDisabled
            ]} 
            onPress={handleRegister}
            disabled={loading || !agreeTerms}
          >
            {loading ? (
              <ActivityIndicator color="#ffffff" size="small" />
            ) : (
              <Text style={styles.registerButtonText}>立即注册</Text>
            )}
          </TouchableOpacity>

          {/* 其他注册方式 - 调整位置将其上移 */}
          <View style={[styles.otherLoginContainer, {marginTop: 5, marginBottom: 8}]}>
            <View style={styles.divider}></View>
            <Text style={styles.otherLoginText}>或使用以下方式直接注册</Text>
            <View style={styles.divider}></View>
          </View>

          {/* 社交登录按钮 - 调整距离 */}
          <View style={[styles.socialButtonsContainer, {marginVertical: 8}]}>
            <TouchableOpacity style={styles.socialButton} onPress={showDevelopingAlert} disabled={loading}>
              <FontAwesome name="weixin" size={24} color="#09BB07" />
            </TouchableOpacity>
            <TouchableOpacity style={styles.socialButton} onPress={showDevelopingAlert} disabled={loading}>
              <FontAwesome name="qq" size={24} color="#2196F3" />
            </TouchableOpacity>
            <TouchableOpacity style={styles.socialButton} onPress={showDevelopingAlert} disabled={loading}>
              <FontAwesome name="weibo" size={24} color="#E91E63" />
            </TouchableOpacity>
          </View>

          {/* 增加底部安全间距，动态适应不同设备 */}
          <View style={{height: Math.max(insets.bottom + 20, 50)}} />
        </ScrollView>
      </View>
    </TouchableWithoutFeedback>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f9f9f9',
  },
  header: {
    minHeight: 180,
    paddingHorizontal: 24,
  },
  backButton: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 16,
  },
  backButtonText: {
    color: '#ffffff',
    fontSize: 16,
    marginLeft: 8,
  },
  headerTextContainer: {
    marginTop: 10,
  },
  welcomeText: {
    fontSize: 28,
    fontWeight: 'bold',
    color: '#ffffff',
    marginBottom: 8,
  },
  subHeaderText: {
    fontSize: 16,
    color: 'rgba(255, 255, 255, 0.8)',
  },
  formContainer: {
    flex: 1,
    backgroundColor: '#ffffff',
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    marginTop: -20,
    paddingHorizontal: 24,
    paddingTop: 24,
  },
  inputGroup: {
    marginBottom: 16,
  },
  label: {
    fontSize: 14,
    fontWeight: '500',
    marginBottom: 8,
    color: '#333',
  },
  requiredMark: {
    color: '#f44336',
  },
  optionalMark: {
    color: '#9e9e9e',
    fontSize: 12,
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    borderWidth: 1,
    borderColor: '#e0e0e0',
    borderRadius: 8,
    backgroundColor: '#f9f9f9',
    height: 50,
  },
  inputIcon: {
    paddingHorizontal: 12,
  },
  input: {
    flex: 1,
    height: 50,
    fontSize: 16,
    color: '#333',
  },
  passwordToggle: {
    padding: 12,
  },
  termsContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 20,
    marginRight: 20,
  },
  termsText: {
    fontSize: 13,
    color: '#666',
    marginLeft: 4,
    flex: 1,
  },
  termsLink: {
    color: '#5e35b1',
    fontWeight: '500',
  },
  registerButton: {
    backgroundColor: '#5e35b1',
    height: 50,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 12,
  },
  registerButtonDisabled: {
    backgroundColor: '#9e9e9e',
  },
  registerButtonText: {
    color: '#ffffff',
    fontSize: 16,
    fontWeight: '600',
  },
  otherLoginContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginVertical: 16,
  },
  divider: {
    flex: 1,
    height: 1,
    backgroundColor: '#e0e0e0',
  },
  otherLoginText: {
    marginHorizontal: 16,
    color: '#666',
    fontSize: 14,
  },
  socialButtonsContainer: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginVertical: 16,
  },
  socialButton: {
    width: 50,
    height: 50,
    borderRadius: 25,
    backgroundColor: '#f5f5f5',
    justifyContent: 'center',
    alignItems: 'center',
    marginHorizontal: 12,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 1.5,
    elevation: 2,
  }
});